import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Card,
  Typography,
  Space,
  Button,
  Avatar,
  Divider,
  Spin,
  message,
  Row,
  Col,
  Tag,
  Modal
} from 'antd';
import {
  ArrowLeftOutlined,
  EyeOutlined,
  LikeOutlined,
  ShareAltOutlined,
  UserOutlined,
  CalendarOutlined,
  FileOutlined,
  DownloadOutlined,
  FileImageOutlined,
  FilePdfOutlined,
  FileWordOutlined,
  FilePptOutlined,
  FileExcelOutlined
} from '@ant-design/icons';
import './WorkView.scss';

const { Title, Text, Paragraph } = Typography;

const WorkView = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [work, setWork] = useState(null);
  const [loading, setLoading] = useState(true);
  const [attachments, setAttachments] = useState([]);

  useEffect(() => {
    loadWork();
  }, [id]);

  const loadWork = async () => {
    try {
      setLoading(true);
      const response = await fetch(`http://211.86.197.10:9091/api/articles/${id}`);
      const result = await response.json();

      console.log('作品数据:', result); // 调试日志

      if (result.success) {
        setWork(result.data);
        
        // 加载附件
        if (result.data.attachments && result.data.attachments.length > 0) {
          console.log('附件数据:', result.data.attachments); // 调试日志
          setAttachments(result.data.attachments);
        } else {
          console.log('没有找到附件数据'); // 调试日志
          // 尝试单独加载附件
          try {
            const attachmentsResponse = await fetch(`http://211.86.197.10:9091/api/articles/${id}/attachments`);
            const attachmentsResult = await attachmentsResponse.json();
            
            console.log('单独加载的附件数据:', attachmentsResult); // 调试日志
            
            if (attachmentsResult.success && attachmentsResult.data.length > 0) {
              setAttachments(attachmentsResult.data);
            }
          } catch (attachmentError) {
            console.error('加载附件失败:', attachmentError);
          }
        }
      } else {
        message.error('作品不存在或已被删除');
        navigate('/');
      }
    } catch (error) {
      console.error('加载作品错误:', error);
      message.error('加载作品失败');
      navigate('/');
    } finally {
      setLoading(false);
    }
  };

  const handleBack = () => {
    navigate(-1);
  };

  const handleShare = () => {
    const url = window.location.href;
    if (navigator.share) {
      navigator.share({
        title: work.title,
        text: `查看作品：${work.title}`,
        url: url
      });
    } else {
      // 复制到剪贴板
      navigator.clipboard.writeText(url).then(() => {
        message.success('链接已复制到剪贴板');
      });
    }
  };

  const handleLike = async () => {
    try {
      // TODO: 实现点赞功能
      message.success('点赞成功');
    } catch (error) {
      message.error('点赞失败');
    }
  };

  const previewAttachment = async (attachment) => {
    try {
      // 检查文档类型
      const isPdf = attachment.mime_type === 'application/pdf';
      const isPdfConvertible = [
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.presentationml.presentation',
        'application/vnd.ms-powerpoint'
      ].includes(attachment.mime_type);

      // 如果是PDF文档，直接预览
      if (isPdf) {
        window.open(`http://211.86.197.10:9091${attachment.file_url}`, '_blank');
        return;
      }

      // 对于Word和PPT文档，优先尝试PDF预览
      if (isPdfConvertible) {
        try {
          const pdfResponse = await fetch(`http://211.86.197.10:9091/api/documents/${attachment.id}/convert-pdf`, {
            method: 'POST'
          });

          const pdfResult = await pdfResponse.json();

          if (pdfResult.success && !pdfResult.data.isPlaceholder) {
            // 直接在新窗口打开PDF
            window.open(`http://211.86.197.10:9091${pdfResult.data.pdfUrl}`, '_blank');
            return;
          }
        } catch (pdfError) {
          console.warn('PDF转换失败，尝试HTML预览:', pdfError);
        }
      }

      // 如果PDF转换失败或不支持，尝试HTML转换
      const isConvertibleDocument = [
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.presentationml.presentation',
        'application/vnd.ms-powerpoint',
        'text/plain'
      ].includes(attachment.mime_type);

      if (isConvertibleDocument) {
        const response = await fetch(`http://211.86.197.10:9091/api/documents/${attachment.id}/convert`, {
          method: 'POST'
        });

        const result = await response.json();

        if (result.success) {
          Modal.info({
            title: `预览: ${attachment.original_name}`,
            width: '90%',
            style: { top: 20 },
            className: 'document-preview-modal',
            content: (
              <div className="document-preview-content">
                <div 
                  dangerouslySetInnerHTML={{ __html: result.data.html }}
                />
              </div>
            ),
            footer: (
              <div style={{ textAlign: 'center' }}>
                <Space>
                  {isPdfConvertible && (
                    <Button 
                      onClick={async () => {
                        try {
                          const pdfResponse = await fetch(`http://211.86.197.10:9091/api/documents/${attachment.id}/convert-pdf`, {
                            method: 'POST'
                          });
                          const pdfResult = await pdfResponse.json();
                          if (pdfResult.success) {
                            window.open(`http://211.86.197.10:9091${pdfResult.data.pdfUrl}`, '_blank');
                          }
                        } catch (error) {
                          message.error('PDF转换失败');
                        }
                      }}
                    >
                      PDF预览
                    </Button>
                  )}
                  <Button 
                    type="primary" 
                    onClick={() => window.open(`http://211.86.197.10:9091${attachment.file_url}`, '_blank')}
                  >
                    在新窗口打开原文件
                  </Button>
                  <Button 
                    onClick={() => {
                      const link = document.createElement('a');
                      link.href = `http://211.86.197.10:9091${attachment.file_url}`;
                      link.download = attachment.original_name;
                      document.body.appendChild(link);
                      link.click();
                      document.body.removeChild(link);
                    }}
                  >
                    下载原文件
                  </Button>
                </Space>
              </div>
            )
          });
          return;
        }
      }

      // 如果转换失败或不支持转换，直接打开原文件
      window.open(`http://211.86.197.10:9091${attachment.file_url}`, '_blank');
    } catch (error) {
      console.error('预览附件失败:', error);
      window.open(`http://211.86.197.10:9091${attachment.file_url}`, '_blank');
    }
  };

  if (loading) {
    return (
      <div className="work-view-loading">
        <Spin size="large" />
        <div className="loading-text">加载中...</div>
      </div>
    );
  }

  if (!work) {
    return (
      <div className="work-view-error">
        <Title level={3}>作品不存在</Title>
        <Button type="primary" onClick={handleBack}>
          返回
        </Button>
      </div>
    );
  }

  return (
    <div className="work-view-container">
      <div className="work-view-header">
        <Button 
          icon={<ArrowLeftOutlined />} 
          onClick={handleBack}
          className="back-button"
        >
          返回
        </Button>
        
        <div className="work-actions">
          <Space>
            <Button 
              icon={<LikeOutlined />} 
              onClick={handleLike}
            >
              点赞 ({work.like_count || 0})
            </Button>
            <Button 
              icon={<ShareAltOutlined />} 
              onClick={handleShare}
            >
              分享
            </Button>
          </Space>
        </div>
      </div>

      <Card className="work-content-card">
        {/* 作品标题 */}
        <div className="work-title-section">
          <Title level={1} className="work-title">
            {work.title}
          </Title>
          
          <div className="work-meta">
            <Space size="large">
              <Space>
                <Avatar 
                  src={work.avatar_url} 
                  icon={<UserOutlined />}
                  size="small"
                />
                <Text strong>{work.username || '匿名用户'}</Text>
              </Space>
              
              <Space>
                <CalendarOutlined />
                <Text type="secondary">
                  {new Date(work.created_at).toLocaleDateString('zh-CN')}
                </Text>
              </Space>
              
              <Space>
                <EyeOutlined />
                <Text type="secondary">{work.view_count || 0} 次浏览</Text>
              </Space>
              
              <Tag color={work.status === 'published' ? 'green' : 'orange'}>
                {work.status === 'published' ? '已发布' : '草稿'}
              </Tag>
            </Space>
          </div>
        </div>

        {/* 封面图片 */}
        {work.cover_image && (
          <div className="work-cover">
            <img 
              src={work.cover_image} 
              alt={work.title}
              className="cover-image"
            />
          </div>
        )}

        <Divider />

        {/* 作品内容 */}
        <div className="work-content">
          <div 
            className="content-html"
            dangerouslySetInnerHTML={{ __html: work.content_html }}
          />
        </div>

        {/* 附件列表 */}
        {attachments.length > 0 && (
          <>
            <Divider />
            <div className="work-attachments">
              <Title level={4}>
                <FileOutlined style={{ marginRight: 8 }} />
                相关附件 ({attachments.length})
              </Title>
              
              <Row gutter={[16, 16]}>
                {attachments.map(attachment => (
                  <Col xs={24} sm={12} md={8} key={attachment.id}>
                    <Card 
                      size="small" 
                      className="attachment-card"
                      hoverable
                      actions={[
                        <Button 
                          type="link" 
                          size="small"
                          icon={<EyeOutlined />}
                          onClick={() => previewAttachment(attachment)}
                        >
                          预览
                        </Button>,
                        <Button 
                          type="link" 
                          size="small"
                          icon={<DownloadOutlined />}
                          onClick={() => {
                            const link = document.createElement('a');
                            link.href = `http://211.86.197.10:9091${attachment.file_url}`;
                            link.download = attachment.original_name;
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);
                          }}
                        >
                          下载
                        </Button>
                      ]}
                    >
                      <Card.Meta
                        avatar={
                          <div style={{ 
                            display: 'flex', 
                            alignItems: 'center', 
                            justifyContent: 'center',
                            width: 40,
                            height: 40,
                            backgroundColor: '#f0f8ff',
                            borderRadius: '8px'
                          }}>
                            {attachment.file_type === 'image' ? (
                              <FileImageOutlined style={{ fontSize: 20, color: '#52c41a' }} />
                            ) : attachment.mime_type?.includes('pdf') ? (
                              <FilePdfOutlined style={{ fontSize: 20, color: '#ff4d4f' }} />
                            ) : attachment.mime_type?.includes('word') || attachment.mime_type?.includes('document') ? (
                              <FileWordOutlined style={{ fontSize: 20, color: '#1890ff' }} />
                            ) : attachment.mime_type?.includes('presentation') || attachment.mime_type?.includes('powerpoint') ? (
                              <FilePptOutlined style={{ fontSize: 20, color: '#fa8c16' }} />
                            ) : attachment.mime_type?.includes('sheet') || attachment.mime_type?.includes('excel') ? (
                              <FileExcelOutlined style={{ fontSize: 20, color: '#52c41a' }} />
                            ) : (
                              <FileOutlined style={{ fontSize: 20, color: '#1890ff' }} />
                            )}
                          </div>
                        }
                        title={
                          <div className="attachment-title" style={{ 
                            fontSize: '14px',
                            fontWeight: 500,
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap'
                          }}>
                            {attachment.original_name}
                          </div>
                        }
                        description={
                          <div className="attachment-description" style={{ fontSize: '12px', color: '#666' }}>
                            <div>大小: {(attachment.file_size / 1024 / 1024).toFixed(2)} MB</div>
                            <div>类型: {attachment.file_type || '文档'}</div>
                            {attachment.mime_type && (
                              <div style={{ fontSize: '11px', color: '#999', marginTop: '4px' }}>
                                {attachment.mime_type.split('/')[1]?.toUpperCase()}
                              </div>
                            )}
                          </div>
                        }
                      />
                    </Card>
                  </Col>
                ))}
              </Row>
            </div>
          </>
        )}
      </Card>
    </div>
  );
};

export default WorkView;